import * as faceapi from "face-api.js";

main()

let faceMatcher = null
const classes = ['amy', 'bernadette', 'howard', 'leonard', 'penny', 'raj', 'sheldon', 'stuart']


async function main(){
    // load model
    await faceapi.nets.ssdMobilenetv1.loadFromUri('http://127.0.0.1:8888/weights')
    await faceapi.nets.faceLandmark68Net.loadFromUri('http://127.0.0.1:8888/weights')
    await faceapi.nets.faceRecognitionNet.loadFromUri('http://127.0.0.1:8888/weights')

    // 获取face样本特征
    faceMatcher = await createBbtFaceMatcher(1)

    const imgEl = document.getElementById('face')

    // 检测图片上的全部face
    const results = await faceapi.detectAllFaces(imgEl).withFaceLandmarks().withFaceDescriptors()

    // 将画布和图片匹配尺寸
    const canvas = document.getElementById('overlay')
    faceapi.matchDimensions(canvas, imgEl)

    // 调整检测图像大小
    const resizedResults = faceapi.resizeResults(results, imgEl)

    resizedResults.forEach(({detection,descriptor})=>{
        // 根据样本特征识别每一个人脸
        const label = faceMatcher.findBestMatch(descriptor).toString()
        const options = {label}
        // 使用自定义文本绘制框DrawBox，将文字添加到canvas中人脸的位置
        const drawBox = new faceapi.draw.DrawBox(detection.box, options)
        drawBox.draw(canvas)
    })

    closeLoading()
}

// 获取图片
function getImageUri(className){
    let ext = '.png'
    return 'http://127.0.0.1:8888/images/names/' + className + ext
}

// 获取face样本特征，提取每个人的第一张图片作为样本
async function createBbtFaceMatcher(num){

    let labeledFaceDescriptors = await Promise.all(classes.map(async className=>{
        let uri = getImageUri(className)
        const img = await faceapi.fetchImage(uri)
        const descriptors = [await faceapi.computeFaceDescriptor(img)]
        return new faceapi.LabeledFaceDescriptors(className ,descriptors)
    }))

    return new faceapi.FaceMatcher(labeledFaceDescriptors)
}